package com.ruoyi.wechat.controller;

import com.ruoyi.wechat.common.ServiceException;
import com.ruoyi.wechat.domain.Order;
import com.ruoyi.wechat.domain.vo.AjaxResult;
import com.ruoyi.wechat.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author lsh
 * @ClassName WxPayController
 * @description: TODO
 * @date 2023年10月24日
 */
@Slf4j
@RestController
@RequestMapping("/pay")
public class WxPayController {

    @Resource
    private WxPayService wxPayService;

    /**
     * 微信预支付
     *
     * @param order
     * @return
     * @throws Exception
     */
    @PostMapping("/wx-jsApi")
    public AjaxResult createOrder(@RequestBody Order order) throws Exception {
        Map<String, Object> payMap = wxPayService.prePay(order.getId());
        if(ObjectUtils.isEmpty(payMap)){
            throw new ServiceException(HttpStatus.SC_NO_CONTENT,"支付金额为0");
        }
        return AjaxResult.success(payMap);
    }


    /**
     * 微信支付回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify/wx-jsApi")
    public AjaxResult payNotify(HttpServletRequest request) throws Exception {
        log.info("-----------------------微信支付回调通知-----------------------");
        //注意：回调接口需要暴露到公网上，且要放开token验证
        return wxPayService.payNotify(request);
    }

    /**
     * 查询支付
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/queryPayOrder")
    public AjaxResult queryPayOrder(@RequestParam("tradeNo") String tradeNo) {
        log.info("-----------------------订单号：" + tradeNo);
        if (tradeNo == null || "".equals(tradeNo)) {
            return AjaxResult.error("订单号为空");
        }
        Transaction transaction = wxPayService.queryPayOrder(tradeNo);
        return AjaxResult.success(transaction);
    }
}
